﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.IO;
using System.Xml.Linq;

namespace NoteBox
{
    public partial class Settings : Form
    {
        decimal snumeric1;
        decimal snumeric2;

        #region Общее
        public Settings(int numberOfPanel)
        {
            InitializeComponent();
            //
            ((RadioButton)Controls.Find("radioButton" + numberOfPanel, true)[0]).Checked = true;
            //
            RegistryAutoLoad();
            numericUpDown1.Value = (int)(Form1.formOpacity1 * 100);
            numericUpDown2.Value = (int)(Form1.formOpacity2 * 100);
            //
            snumeric1 = numericUpDown1.Value;
            snumeric2 = numericUpDown2.Value;
            //
            for (int i = 0; i < MailForm.mails.Count; i++)
            {
                listView1.Items.Add(MailForm.mails[i].mMailName);
            }
            //
            MailProfileSettingsCreate();
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            RegistryAutoSave();
            CloseCl();
        }
        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Form1.formOpacity1 = (double)(snumeric1 / 100);
            Form1.formOpacity2 = (double)(snumeric2 / 100);
            CloseCl();
        }

        private void Settings_FormClosing(object sender, FormClosingEventArgs e)
        {
            CloseCl();
        }
        private void CloseCl()
        {
            this.Dispose();
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            Form1.formOpacity1 = (double)(numericUpDown1.Value/100);
            if (numericUpDown1.Value > numericUpDown2.Minimum)
            {
                numericUpDown2.Minimum = numericUpDown1.Value;
            }
            else numericUpDown2.Minimum = 50;
        }
        private void numericUpDown2_ValueChanged(object sender, EventArgs e)
        {
            Form1.formOpacity2 = (double)(numericUpDown2.Value / 100);
            if (numericUpDown2.Value < numericUpDown1.Maximum)
            {
                numericUpDown1.Maximum = numericUpDown2.Value;
            }
            else numericUpDown1.Maximum = 80;
        }

        #region Сохранение инфы о автозагрузке
        public void RegistryAutoLoad()
        {
            // автозагрузка
            const string userRoot = "HKEY_CURRENT_USER";
            const string subkey = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
            const string keyName = userRoot + "\\" + subkey;
            if ((string)Registry.GetValue(keyName, "NoteBox", "false") != "false")
                checkBoxAutoLoad.Checked = true;
        }
        public void RegistryAutoSave()
        {
            // автозагрузка
            const string userRoot = "HKEY_CURRENT_USER";
            const string subkey = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
            const string keyName = userRoot + "\\" + subkey;
            if (checkBoxAutoLoad.Checked)
               Registry.SetValue(keyName, "NoteBox", Application.ExecutablePath);
            else
            {
                RegistryKey test9999 = Registry.CurrentUser.CreateSubKey(subkey);
                test9999.DeleteValue("NoteBox",false);
            }
        }
        #endregion

        #endregion

        #region Почта - загрузка профилей настроек и сохраненных

        /// <summary>
        /// Профили c настройками
        /// </summary>
        class MailProfileSettings
        {
            public string name;
            public string server;
            public int port;
            public bool ssl;
            public bool addservertologin;

            public MailProfileSettings(string _name, string _server, int _port, bool _ssl, bool _addserv)
            {
                name = _name;
                server = _server;
                port = _port;
                ssl = _ssl;
                addservertologin = _addserv;
            }
        }
        List<MailProfileSettings> mailProfilesSettings = new List<MailProfileSettings>();
        public bool MailProfileSettingsLoad()
        {
            if (!File.Exists(Form1.MailProfilesFileName))
                return false;
            XDocument XDoc = XDocument.Load(Form1.MailProfilesFileName);
            foreach (XElement prf in XDoc.Element("MailProfiles").Elements())
            {
                try
                {
                    mailProfilesSettings.Add(new MailProfileSettings((string)prf.Element("Name"),
                        (string)prf.Element("Server"), (int)prf.Element("Port"), (bool)prf.Element("Ssl"), (bool)prf.Element("AddEMailLogin")));
                }
                catch
                {
                    return false;
                }
                
            }
            return true;
        }
        public void MailProfileSettingsCreate()
        {
            if (!MailProfileSettingsLoad()) // если не загрузились
            {
                mailProfilesSettings.Add(new MailProfileSettings("gmail.com", "pop.gmail.com", 995, true,true));
                mailProfilesSettings.Add(new MailProfileSettings("mail.ru", "pop.mail.ru", 110, false,false));
                mailProfilesSettings.Add(new MailProfileSettings("yandex.ru", "pop.yandex.ru", 110, false,false));
                mailProfilesSettings.Add(new MailProfileSettings("meta.ua", "pop.meta.ua", 110, false,true));
            }
        }

        // клики
        private void radioButton12_Click(object sender, EventArgs e)
        {
            panel1.Visible = radioButton1.Checked;
            panel2.Visible = radioButton2.Checked;
        }
        
        // создать новый ящик
        private void button1_Click(object sender, EventArgs e)
        {
            groupBox1.Enabled = true;
            groupBoxManual.Enabled = true;
            textBoxEmail.Focus();
        }

        // Сохранить ящик
        private void buttonSaveMail_Click(object sender, EventArgs e)
        {
            if ((textBoxEmail.Text == "") || (textBoxPass.Text == "") || (textBoxLogin.Text == "") || (textBoxPort.Text == "")|| (textBoxServer.Text == ""))
            {
                MessageBox.Show("Введите все данные!");
                return;
            }
            groupBox1.Enabled = false;
            groupBoxManual.Enabled = false;
            if (wasSelectedFromListBoxIndex == -1)
            {
                MailForm.mails.Add(new mMail(textBoxEmail.Text, textBoxLogin.Text, textBoxPass.Text
                    , textBoxServer.Text, Int32.Parse(textBoxPort.Text), checkBoxSSL.Checked
                    , checkBoxAutoCheck.Checked, ((int)numericUpDownMinutes.Value * 60)));
                MailForm.mails[MailForm.mails.Count - 1].Parent = Form1.formMail;
                MailForm.mails[MailForm.mails.Count - 1].BringToFront();
                listView1.Items.Add(textBoxEmail.Text);
                //
                int Lleft = 12;
                if (MailForm.mailButtons.Count - 1 >= 0) Lleft = MailForm.mailButtons[MailForm.mailButtons.Count - 1].Left + MailForm.mailButtons[MailForm.mailButtons.Count - 1].Width;
                MailForm.mailButtons.Add(new mButton(MailForm.mails[MailForm.mails.Count - 1].mMailName, MailForm.mails.Count - 1, 11, Lleft));
            }
            else
            {
                listView1.Items[wasSelectedFromListBoxIndex].Text = textBoxEmail.Text;
                MailForm.mails[wasSelectedFromListBoxIndex].mMailName = textBoxEmail.Text;
                MailForm.mails[wasSelectedFromListBoxIndex].mPassword = textBoxPass.Text;
                MailForm.mails[wasSelectedFromListBoxIndex].mLogin = textBoxLogin.Text;
                MailForm.mails[wasSelectedFromListBoxIndex].mServer = textBoxServer.Text;
                MailForm.mails[wasSelectedFromListBoxIndex].mPort = Int32.Parse(textBoxPort.Text);
                MailForm.mails[wasSelectedFromListBoxIndex].mSsl = checkBoxSSL.Checked;
                MailForm.mails[wasSelectedFromListBoxIndex].mAutoLoad = checkBoxAutoCheck.Checked;
                MailForm.mails[wasSelectedFromListBoxIndex].mAutoLoadTime = ((int)numericUpDownMinutes.Value)*60;
                MailForm.mailButtons[wasSelectedFromListBoxIndex].Name = textBoxEmail.Text;
                MailForm.mailButtons[wasSelectedFromListBoxIndex].Text = textBoxEmail.Text;
            }
            Form1.TaskChanged = true;
            textBoxEmail.Text = ""; textBoxPass.Text = ""; textBoxLogin.Text = ""; textBoxPort.Text = ""; textBoxServer.Text = "";
            wasSelectedFromListBoxIndex = -1;
        }
        //
        private void buttonCancelMail_Click(object sender, EventArgs e)
        {
            groupBox1.Enabled = false;
            groupBoxManual.Enabled = false;
            textBoxEmail.Text = ""; textBoxPass.Text = ""; textBoxLogin.Text = ""; textBoxPort.Text = ""; textBoxServer.Text = "";
            wasSelectedFromListBoxIndex = -1;
        }

        #endregion

        private void textBoxEmail_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (((e.KeyChar >= 'a') && (e.KeyChar <= 'z')) || ((e.KeyChar >= 'A') && (e.KeyChar <= 'Z')) ||
                ((e.KeyChar >= '0') && (e.KeyChar <= '9')) || e.KeyChar == '.'
                || e.KeyChar == '_' || e.KeyChar == '@' || e.KeyChar == '-' || e.KeyChar == 09 || e.KeyChar == 08)
            {}
            else e.KeyChar = e.KeyChar = Convert.ToChar(0);
            if (textBoxEmail.Text.Contains('@') && e.KeyChar=='@')
                e.KeyChar = e.KeyChar = Convert.ToChar(0);
        }

        private void textBoxEmail_KeyUp(object sender, KeyEventArgs e)
        {
            if (textBoxEmail.Text.Contains('@'))
            {
                textBoxLogin.Text = textBoxEmail.Text.Split('@')[0];
                foreach (MailProfileSettings mp in mailProfilesSettings)
                {
                    if (mp.name == textBoxEmail.Text.Split('@')[1])
                    {
                        textBoxServer.Text = mp.server.ToString();
                        textBoxPort.Text = mp.port.ToString();
                        checkBoxSSL.Checked = mp.ssl;
                        if (mp.addservertologin)
                            textBoxLogin.Text = textBoxEmail.Text;
                    }
                }
            }
            else
                textBoxLogin.Text = textBoxEmail.Text;

        }
        
        // выбор ящика
        int wasSelectedFromListBoxIndex = -1;
        private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            wasSelectedFromListBoxIndex = e.ItemIndex;
            textBoxEmail.Text = MailForm.mails[e.ItemIndex].mMailName;
            textBoxPass.Text = MailForm.mails[e.ItemIndex].mPassword;
            textBoxLogin.Text = MailForm.mails[e.ItemIndex].mLogin;
            int po = MailForm.mails[e.ItemIndex].mPort;
            textBoxPort.Text = po.ToString();
            textBoxServer.Text = MailForm.mails[e.ItemIndex].mServer;
            checkBoxSSL.Checked = MailForm.mails[e.ItemIndex].mSsl;
            checkBoxAutoCheck.Checked = MailForm.mails[e.ItemIndex].mAutoLoad;
            numericUpDownMinutes.Value = (decimal)(MailForm.mails[e.ItemIndex].mAutoLoadTime/60);
            groupBox1.Enabled = true;
            groupBoxManual.Enabled = true;
            textBoxEmail.Focus();
        }

 


        

        
    }
}
